import React, { PureComponent } from 'react';
import { connect } from 'dva';
import myStyle from './index.less';
import { Switch } from 'antd';

function checkAll(item) {
  return item.checked == false;
}
class TradeDirection extends PureComponent {
  state = {
    switchList: [],
  };

  componentDidMount() {
    this.props.onRef(this);
    this.setState({
      switchList: _.cloneDeep(this.props.dataList),
    });
  }

  componentDidUpdate(preProps) {
    if (JSON.stringify(preProps.dataList) !== JSON.stringify(this.props.dataList)) {
      this.setState({
        switchList: _.cloneDeep(this.props.dataList),
      });
    }
  }

  switchChange = (checked, type) => {
    const { switchList } = this.state;
    if (type == 'all') {
      switchList.map((item) => {
        item.checked = checked;
      });
    } else {
      switchList.map((item, key) => {
        if (key == type) {
          item.checked = checked;
        }
      });
    }
    this.setState({ switchList: [...switchList] });
  };

  // 用户点击提交
  submit = () => {
    const { switchList } = this.state;
    const obj = {};
    switchList.map((item) => {
      obj[item.value] = item.checked;
    });
    obj.transactionDirectionControl = !switchList.some(checkAll);
    return obj;
  };

  render() {
    const { switchList } = this.state;
    return (
      <div className={myStyle.tradeDirection}>
        <ul>
          <li>
            <span>交易方向</span>
            <span style={{ marginRight: '8px' }}>是否触发</span>
            <span>
              <Switch checkedChildren='开' unCheckedChildren='关' checked={!switchList.some(checkAll)} onChange={(e) => this.switchChange(e, 'all')} />
            </span>
          </li>
          {switchList.map((item, key) => {
            return (
              <li key={key}>
                <span>{item.name}</span>
                <span>
                  <Switch checkedChildren='开' unCheckedChildren='关' checked={item.checked} onChange={(e) => this.switchChange(e, key)} />
                </span>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}
export default connect(({ limitSetting, dictionaryM, userM: user, loading }) => ({
  limitSetting,
  dictionaryM,
  user,
  loading,
}))(TradeDirection);
